package cn.gdut.chengcai.admin.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.gdut.chengcai.base.ConstantUtil;
import cn.gdut.chengcai.base.CountUtil;
import cn.gdut.chengcai.base.JsonUtil;
import cn.gdut.chengcai.base.MessageUtil;
import cn.gdut.chengcai.base.RequestUtil;
import cn.gdut.chengcai.base.ResponseData;
import cn.gdut.chengcai.entity.AdminInfo;
import cn.gdut.chengcai.entity.AdminInfoExample;
import cn.gdut.chengcai.entity.BlacklistInfo;
import cn.gdut.chengcai.entity.BlacklistInfoExample;
import cn.gdut.chengcai.entity.CountInfo;
import cn.gdut.chengcai.entity.ValidateLogInfo;
import cn.gdut.chengcai.service.AdminInfoService;
import cn.gdut.chengcai.service.BlacklistInfoService;
import cn.gdut.chengcai.service.CountInfoService;
import cn.gdut.chengcai.service.ValidateLogInfoService;
import cn.gdut.chengcai.vo.AdminInfoVo;
import cn.gdut.chengcai.vo.CountInfoVo;

@Controller
@RequestMapping("/admin/auth")
public class Admin_AuthController {

	// public static LogUtil log =
	// LogUtil.getInstance(AuthController.class.getName());

	public static int MAX_ATTEMPT_NUMBER = 3;

	@Autowired
	protected AdminInfoService adminInfoService;

	@Autowired
	protected BlacklistInfoService blacklistInfoService;

	@Autowired
	protected ValidateLogInfoService validateLogInfoService;

	@Autowired
	protected CountInfoService countInfoService;

	/**
	 * 首页
	 */
	@RequestMapping("/index")
	public String index(HttpSession session, ModelMap map) {

		CountInfo entity = countInfoService.selectByPrimaryKey(1L);
		CountInfoVo vo = new CountInfoVo();
		try {
			CountUtil.fillVo(entity, vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("entity", vo);

		return "/admin/index";
	}

	/**
	 * 登录页面
	 */
	@RequestMapping("/login")
	public String login() {
		return "/admin/login";
	}

	/**
	 * 登录操作
	 */
	@RequestMapping(value = "/loginAction", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData<Object> loginAction(@RequestBody String jsonString, HttpServletRequest request,
			HttpSession session) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		result.setMessage(MessageUtil.PASSWORD_NOT_MATCH);

		AdminInfoVo param = (AdminInfoVo) JsonUtil.fromJson(jsonString, AdminInfoVo.class);

		String ip = RequestUtil.getRemoteHost(request);

		try {
			if (param != null && param.getUsername() != null && param.getPassword() != null) {

				AdminInfoExample example = new AdminInfoExample();
				example.createCriteria().andUsernameEqualTo(param.getUsername())
						.andPasswordEqualTo(param.getPassword());
				AdminInfo account = adminInfoService.selectByExample(example).get(0);
				if (account != null) {
					// 判断是否在黑名单中
					BlacklistInfoExample blInfoExample = new BlacklistInfoExample();
					BlacklistInfoExample.Criteria blInfoCriteria = blInfoExample.createCriteria();
					blInfoCriteria.andMemberIdEqualTo(account.getId()).andMemberSnEqualTo(account.getSn())
							.andMemberUsernameEqualTo(account.getUsername()).andIsAdminEqualTo(true);
					List<BlacklistInfo> blInfoList = blacklistInfoService.selectByExample(blInfoExample);
					if ((blInfoList != null) && (blInfoList.size() > 0)) {
						result.setMessage(MessageUtil.BLACK_LIST_ACCOUNT);
						return result;
					}
					if (null == account.getTotalLoginNum()) {
						account.setTotalLoginNum(1);
					} else {
						account.setTotalLoginNum(account.getTotalLoginNum() + 1);
					}
					account.setLastestLoginIp(ip);
					account.setLastestLoginTime(new Date());
					adminInfoService.updateByPrimaryKey(account);

					session.setAttribute(ConstantUtil.STR_ADMIN, account);
					// session.removeAttribute(ConstantUtil.SESSION_IS_LOCK_SCREEN);
					result.setMessage("");
					result.setIsSuccess(true);
				}
			}
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
			// log.error(e.getMessage(), e);
		} finally {

			ValidateLogInfo entity = new ValidateLogInfo();
			entity.setName(param.getUsername());
			entity.setIp(ip);
			entity.setDescription(result.getMessage());
			entity.setIsAdmin(false);
			entity.setIsSuccessed(result.getIsSuccess());
			entity.setCreateTime(new Date());
			validateLogInfoService.insert(entity);

		}
		return result;
	}

	/**
	 * 注销操作
	 */
	@RequestMapping("/logoutAction")
	public String logoutAction(HttpSession session) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {
			// session.invalidate();
			session.removeAttribute(ConstantUtil.STR_ADMIN);
			result.setIsSuccess(true);
		} catch (Exception e) {
			// log.error(e.getMessage(), e);
		}
		return "redirect:/admin/auth/login.do";
	}
}